<template>
  <div class="sign-in">
    <Header isRegister />
    <div class="form-container">
      <a-form ref="formRef" :model="formData">
        <a-form-item
          name="mobile"
          :rules="[
            {
              validator: checkMobile,
              trigger: 'blur',
            },
          ]"
        >
          <a-input
            size="large"
            :placeholder="$t('form.register.form.item_1.rules.error_1')"
            allow-clear
            :maxlength="30"
            v-model:value.trim="formData.mobile"
          >
            <template #prefix
              ><svg
                class="prefix-icon"
                width="20"
                height="20"
                viewBox="0 0 20 20"
                fill="none"
                xmlns="http://www.w3.org/2000/svg"
              >
                <circle
                  cx="10"
                  cy="6.66667"
                  r="4.16667"
                  stroke="#CCD6DE"
                  stroke-width="1.25"
                />
                <path
                  d="M17.5 17.5C17.5 16.1739 16.7098 14.9021 15.3033 13.9645C13.8968 13.0268 11.9891 12.5 10 12.5C8.01088 12.5 6.10322 13.0268 4.6967 13.9645C3.29018 14.9021 2.5 16.1739 2.5 17.5"
                  stroke="#CCD6DE"
                  stroke-width="1.25"
                />
              </svg>
            </template>
          </a-input>
        </a-form-item>
        <a-form-item name="captcha" 
          :rules="[
            {
              validator: checkCaptcha,
              trigger: 'blur',
            },
          ]">
          <a-input
            size="large"
            :placeholder="$t('form.code.placeholder')"
            allow-clear
            :maxlength="30"
            v-model:value.trim="formData.captcha"
          >
            <template #prefix
              ><svg
                width="20"
                height="20"
                viewBox="0 0 20 20"
                fill="none"
                xmlns="http://www.w3.org/2000/svg"
              >
                <path
                  d="M2.5 6.29075C2.5 5.64791 2.86971 5.06237 3.45011 4.78599L9.28345 2.00821C9.73676 1.79234 10.2632 1.79234 10.7166 2.00821L16.5499 4.78599C17.1303 5.06237 17.5 5.64791 17.5 6.29075V8.79254C17.5 11.536 16.1497 14.1037 13.8893 15.6585L10.4723 18.0088C10.1878 18.2045 9.81218 18.2045 9.52774 18.0088L6.11072 15.6585C3.85033 14.1037 2.5 11.536 2.5 8.79254L2.5 6.29075Z"
                  stroke="#CCD6DE"
                  stroke-width="1.25"
                />
                <path
                  d="M5.83301 9.58333L9.58301 12.5L14.583 7.5"
                  stroke="#CCD6DE"
                  stroke-width="1.25"
                />
              </svg>
            </template>
            <template #suffix>
              <div class="code-suffix">
                <div
                  class="send-code"
                  :class="validMobile ? '' : 'disabled'"
                  @click="sendCode"
                  v-if="!tempCaptcha"
                >
                  {{ $t("form.code.get_code") }}
                </div>
                <template v-else>
                  <div class="resend-code" v-if="timeCountDown">
                    {{ timerValue }}s
                  </div>
                  <div
                    :class="validMobile ? '' : 'disabled'"
                    @click="sendCode"
                    v-else
                  >
                    {{ $t("form.code.re_get_code") }}
                  </div>
                </template>
              </div>
            </template>
          </a-input>
        </a-form-item>
        <a-form-item name="password" 
          :rules="[
            {
              validator: checkPassword,
              trigger: 'blur',
            },
          ]">
          <a-input-password
            size="large"
            :maxlength="30"
            type="password"
            :placeholder="$t('form.register.form.item_2.rules.error_1')"
            allow-clear
            v-model:value.trim="formData.password"
          >
            <template #prefix>
              <svg
                class="prefix-icon"
                width="20"
                height="20"
                viewBox="0 0 20 20"
                fill="none"
                xmlns="http://www.w3.org/2000/svg"
              >
                <rect
                  x="2.5"
                  y="7.5"
                  width="15"
                  height="10"
                  rx="1.66667"
                  stroke="#CCD6DE"
                  stroke-width="1.25"
                />
                <path
                  d="M13.3333 7.5V5.83333C13.3333 3.99238 11.8409 2.5 9.99996 2.5V2.5C8.15901 2.5 6.66663 3.99238 6.66663 5.83333V7.5"
                  stroke="#CCD6DE"
                  stroke-width="1.25"
                />
                <path
                  fill-rule="evenodd"
                  clip-rule="evenodd"
                  d="M10.8071 13.9592C11.3196 13.6749 11.6666 13.1283 11.6666 12.5007C11.6666 11.5802 10.9204 10.834 9.99992 10.834C9.07944 10.834 8.33325 11.5802 8.33325 12.5007C8.33325 13.1283 8.68021 13.6749 9.19279 13.9592C9.17568 14.0257 9.16659 14.0955 9.16659 14.1673V15.0007C9.16659 15.4609 9.53968 15.834 9.99992 15.834C10.4602 15.834 10.8333 15.4609 10.8333 15.0007V14.1673C10.8333 14.0955 10.8242 14.0257 10.8071 13.9592Z"
                  fill="#CCD6DE"
                />
              </svg>
            </template>
          </a-input-password>
        </a-form-item>
        <a-form-item name="repassword" 
          :rules="[
            {
              validator: checkRePassword,
              trigger: 'blur',
            },
          ]">
          <a-input-password
            size="large"
            allow-clear
            type="password"
            :maxlength="30"
            v-model:value.trim="formData.repassword"
            :placeholder="$t('form.register.form.item_3.rules.error_1')"
          >
            <template #prefix>
              <svg
                class="prefix-icon"
                width="20"
                height="20"
                viewBox="0 0 20 20"
                fill="none"
                xmlns="http://www.w3.org/2000/svg"
              >
                <rect
                  x="2.5"
                  y="7.5"
                  width="15"
                  height="10"
                  rx="1.66667"
                  stroke="#CCD6DE"
                  stroke-width="1.25"
                />
                <path
                  d="M13.3333 7.5V5.83333C13.3333 3.99238 11.8409 2.5 9.99996 2.5V2.5C8.15901 2.5 6.66663 3.99238 6.66663 5.83333V7.5"
                  stroke="#CCD6DE"
                  stroke-width="1.25"
                />
                <path
                  fill-rule="evenodd"
                  clip-rule="evenodd"
                  d="M10.8071 13.9592C11.3196 13.6749 11.6666 13.1283 11.6666 12.5007C11.6666 11.5802 10.9204 10.834 9.99992 10.834C9.07944 10.834 8.33325 11.5802 8.33325 12.5007C8.33325 13.1283 8.68021 13.6749 9.19279 13.9592C9.17568 14.0257 9.16659 14.0955 9.16659 14.1673V15.0007C9.16659 15.4609 9.53968 15.834 9.99992 15.834C10.4602 15.834 10.8333 15.4609 10.8333 15.0007V14.1673C10.8333 14.0955 10.8242 14.0257 10.8071 13.9592Z"
                  fill="#CCD6DE"
                />
              </svg>
            </template>
          </a-input-password>
        </a-form-item>
        <a-form-item>
          <div class="footer">
            <div>
              <a-checkbox v-model:checked="formData.checked">
                <div>{{ $t("form.login.agree") }}</div>
              </a-checkbox>
              <span v-if="locale != 'cn'"><br />&nbsp;&nbsp;&nbsp;</span>
              <a @click="showAgree" style="vertical-align: top" target="_blank"
                >《{{ $t("btnText.user_agreement") }}》</a
              >
            </div>
            <div>
              {{ $t("form.login.forget_password") }}？<br
                v-if="locale != 'cn'"
              /><span @click="navigateTo('/recover')">{{
                $t("btnText.recover_password")
              }}</span>
            </div>
          </div>
        </a-form-item>
      </a-form>
    </div>
    <div class="btns">
      <a-button
        :class="hasValue ? '' : 'opacity-4'"
        type="primary"
        size="large"
        block
        @click="Register"
        :loading="isSubmiting"
        >{{ $t("btnText.imed_register") }}</a-button
      >
    </div>
    <!-- 用户协议弹窗 -->
    <a-modal
      v-model:visible="showAgreement"
      :title="$t('btnText.user_agreement')"
      width="50vw"
      :footer="null"
      :closable="false"
      class="user-agreement-modal"
    >
      <div class="raw-html scroll-y" ref="readScroll">
        <div
          class="content"
          style="overflow: hidden"
          v-html="useAgreeUrl"
        ></div>
      </div>
      <div
        class="footer-btn"
        style="display: flex; justify-content: center; margin-top: 10px"
      >
        <a-button
          type="primary"
          @click="readAgreeBtn"
          :class="validReadAgree || isReadAgree ? '' : 'opacity-4'"
          >{{ $t("btnText.read_agree") }}</a-button
        >
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { message } from "ant-design-vue";
import type { Rule } from "ant-design-vue/es/form";
import Header from "./Header.vue";
import { postEmailRegister, postPhoneRegister } from "../../../api/member";
import { postSendEmailCode, postSendPhoneCode } from "../../../api/api";
import {
  computed,
  getCurrentInstance,
  nextTick,
  onBeforeUnmount,
  reactive,
  ref,
} from "vue";
import type { RegisterParams } from "../../../types/member";
import { RegEmail, RegMobile, RegPassword } from "../../../data/reg";
import { useGlobalStore } from "../../../store";
import { useRouter } from "vue-router";

const { useAgreeUrl } = useGlobalStore();

const { locale, locales, setLocale } = useI18n();
const $t = getCurrentInstance()?.appContext.config.globalProperties.$t;

const readScroll = ref();
const isAddEvent = ref(false);
const showAgreement = ref(false);
const isReadAgree = ref(false);
const validReadAgree = ref(false);
const showAgree = () => {
  showAgreement.value = true;
  if (isAddEvent.value) return;
  setTimeout(() => {
    nextTick(() => {
      readScroll.value.addEventListener("scroll", handleScroll);
    });
  });
  isAddEvent.value = true;
};
const handleScroll = (e) => {
  let threshold = 20;
  let scrollTop = e.target.scrollTop;
  let clientHeight = e.target.clientHeight;
  let scrollHeight = e.target.scrollHeight;
  if (scrollTop + clientHeight + threshold > scrollHeight) {
    validReadAgree.value = true;
  } else {
    validReadAgree.value = false;
  }
};

const readAgreeBtn = () => {
  if (validReadAgree.value || isReadAgree.value) {
    isReadAgree.value = true;
    showAgreement.value = false;
  }
};

onBeforeUnmount(() => {
  readScroll.value?.removeEventListener("scroll", handleScroll);
});
const formData = reactive<RegisterParams & { checked: boolean }>({
  mobile: "",
  captcha: "",
  password: "",
  repassword: "",
  checked: false,
});

let tempCaptcha = ref();
const validMobile = ref(false);

const checkMobile = async (_rule: Rule, value: string) => {
  if (!value) {
    validMobile.value = false;
    return Promise.reject($t("form.register.form.item_1.rules.error_1"));
  }
  let regEmail = RegEmail;
  if (!regEmail.test(value)) {
    validMobile.value = false;
    return Promise.reject($t("reg_rules.email"));
  } else {
    validMobile.value = true;
    return Promise.resolve();
  }
};
const checkCaptcha = async (_rule: Rule, value: string) => {
  if (!tempCaptcha.value) {
    return Promise.reject($t("form.code.error_1"));
  }
  if (value != tempCaptcha.value) {
    return Promise.reject($t("form.code.error_2"));
  } else {
    return Promise.resolve();
  }
};
const checkPassword = async (_rule: Rule, value: string) => {
  let reg = RegPassword;
  if (!value) {
    return Promise.reject($t("form.register.form.item_2.rules.error_1"));
  }
  if (!reg.test(value)) {
    return Promise.reject($t("reg_rules.password"));
  } else {
    return Promise.resolve();
  }
};
const checkRePassword = async (_rule: Rule, value: string) => {
  let password = formData.password;
  if (!value) {
    return Promise.reject($t("form.register.form.item_3.rules.error_1"));
  }
  if (value !== password) {
    return Promise.reject($t("form.register.form.item_3.rules.no_match"));
  } else {
    return Promise.resolve();
  }
};

// 获取验证码
let timer: any = null;
const timeCountDown = ref(false);
const timerValue = ref(60);

const decreseNumber = () => {
  if (timer) return;
  timeCountDown.value = true;
  timer = setInterval(() => {
    if (timerValue.value === 0) {
      timerValue.value = 60;
      timeCountDown.value = false;
      clearInterval(timer);
      timer = null;
    }
    timerValue.value--;
  }, 1000);
};

const sendCode = async () => {
  if (!validMobile.value) return;
  // 发送邮箱验证码
  let res = await postSendEmailCode({
    email: formData.mobile!,
    type: "register",
    lang: "cn",
  });
  if (res.code === 200) {
    tempCaptcha.value = res.captcha!;
    message.success($t("form.code.send_code"));
    decreseNumber();
  } else {
    message.error(res.msg);
  }
};

const formRef = ref();

const isSubmiting = ref(false);

// 注册
const Register = () => {
  if (!hasValue.value) return;
  if (!formData.checked || !isReadAgree.value)
    return message.warning($t("message.agree_read"));
  formRef.value.validate().then(async () => {
    isSubmiting.value = true;
    formData.email = formData.mobile;
    let params = Object.assign({}, formData);
    delete params.mobile;
    let res = await postEmailRegister(params);
    isSubmiting.value = false;
    if (res.code === 200) {
      message.success($t("message.register_success"));
      tempCaptcha.value = "";
      timerValue.value = 0;
      // 重置表单
      formRef.value.resetFields();
      goto("/login");
    } else {
      message.error($t("message.error.register"));
    }
  });
};

// 绑定按钮透明度
const hasValue = computed(() => {
  let flag = false;
  if (formData.mobile) flag = true;
  if (formData.captcha) flag = true;
  if (formData.password) flag = true;
  if (formData.repassword) flag = true;
  return flag;
});
</script>

<style lang="less">
.user-agreement-modal {
  .ant-modal-header {
    text-align: center;
  }
  .raw-html {
    height: 65vh;
  }
}
</style>
<style scoped lang="less">
@import url("./common.less");
.code-suffix {
  font-size: 21px;
  color: #3d88f2;
  & > div {
    cursor: pointer;
    &.disabled {
      color: #ccd6de;
      cursor: not-allowed;
    }
  }
  .resend-code {
    color: #ccd6de;
  }
}

.footer {
  a {
    color: var(--yd-primary-color) !important;
  }
}
</style>
